//
//  YWUnfinishInspectionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWUnfinishInspectionTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "MJRefresh.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWUnfinishInspectionMissionCell.h"

#import "YWInspectionMissionManager.h"

#import "YWInspectionDetailViewController.h"
#import "YWInspectionLocationViewController.h"
#import "YWEwinManager.h"
//#import "YWReplyManager.h"
//#import "YWNoReadReplyTableViewController.h"

@interface YWUnfinishInspectionTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    NSInteger page;
    BOOL needReload;
}
@property (nonatomic, strong) NSArray* inspectionMissions;
@end

@implementation YWUnfinishInspectionTableViewController
//- (instancetype)init{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self setupTableview];
    [self setupNotifications];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHandleInspectionMission) name:KRefreshInspectionTimeLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHandleInspectionMission) name:KRefreshAssignInspectionMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHandleInspectionMission) name:KRefreshDeleteInspectionMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHandleInspectionMission) name:KRefreshModifyInspectionMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestPatrolLineComplete:) name:KRefreshModifyInspectionLineNotification object:nil];
}

- (void)setupTableview{
    [self.tableView registerClass:[YWUnfinishInspectionMissionCell class] forCellReuseIdentifier:YWUnfinishInspectionMissionCellIdentifier];
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    YWWeakSelf(weakSelf);
    [[YWInspectionMissionManager shareManager] requestInspectionMissionWithPage:page pageSize:10 complete:^(BOOL success) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [weakSelf requestPatrolLineComplete:^(BOOL success) {
                    if (refreshType == YWTableViewFreshTypeDown) {
                        [weakSelf.tableView.mj_header endRefreshing];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                    weakSelf.inspectionMissions = nil;
                    [weakSelf.tableView reloadData];
                }];
                NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
                [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeInspection];
            }else{
                if (refreshType == YWTableViewFreshTypeDown) {
                    [weakSelf.tableView.mj_header endRefreshing];
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        });
    }];
}

- (void)requestPatrolLineComplete:(void (^)(BOOL))complete{
    NSArray *inspectionLineArray = [[YWInspectionMissionManager shareManager] needRequestInspectionlLines];
    if (inspectionLineArray.count) {
        [[YWInspectionMissionManager shareManager] requestInspectionLineWithLineArray:inspectionLineArray complete:^(BOOL success) {
            if (complete) {
                complete(success);
            }
        }];
    }else{
        if (complete) {
            complete(NO);
        }
    }
}

- (NSArray*)inspectionMissions
{
    if (!_inspectionMissions) {
        NSArray *missions = [[NSArray alloc]initWithArray:[[YWInspectionMissionManager shareManager] inspectionMissionsWithPage:page]];
        _inspectionMissions = missions;
    }
    return _inspectionMissions;
}

#pragma mark - UITableViewDataSource
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    return [tableView fd_heightForCellWithIdentifier:YWUnfinishInspectionMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWUnfinishInspectionMissionCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.inspectionMissions.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (void)configureCell:(YWUnfinishInspectionMissionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWInspectionMissionModel* mission = self.inspectionMissions[indexPath.section];
    cell.missionModel = mission;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWUnfinishInspectionMissionCell* cell = [tableView dequeueReusableCellWithIdentifier:YWUnfinishInspectionMissionCellIdentifier];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWInspectionMissionModel* mission = self.inspectionMissions[indexPath.section];
    if (mission.inspectionLine.lineType==YWInspectionLineTypeEquipment) {//设备巡查详情
        YWInspectionDetailViewController *detailVC = [[YWInspectionDetailViewController alloc] init];
        detailVC.inspectionMission = mission;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else{//综合巡查
        YWInspectionLocationViewController *locationMissionVC = [[YWInspectionLocationViewController alloc] init];
        locationMissionVC.inspectionMission = mission;
        [self.navigationController pushViewController:locationMissionVC animated:YES];
    }
    
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;//10;
}

#pragma mark - table view section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWUnfinishInspectionMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customYellowColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    YWInspectionMissionModel* inspectionMission = self.inspectionMissions[section];
    NSString *lineName = inspectionMission.inspectionLine.inspectionLineName?inspectionMission.inspectionLine.inspectionLineName:@"";
    return lineName;
}

-(NSString *)getMissionManString:(NSArray *)targeArray{
    NSString *handlers = [YWCommonTool handlerNamesWithHandlers:targeArray];
    NSString *resultStr = [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"inspectionExecutor", nil),handlers];
    return resultStr;
}

- (void)refreshHandleInspectionMission{
    needReload = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (needReload) {
        needReload = NO;
        _inspectionMissions = nil;
        [self.tableView reloadData];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
